<template>
    <div class="index" id="play">
        <div id="web_bg" :style="webBg"></div>
        <div class="m-close" v-if="isAppEnv" @click="closePage">
            <img src="./../assets/close3.png">
        </div>

        <div class="head clear" @click="shiftLogin">
            <div class="img fl">
                <img :src="userAvatar">
            </div>

            <div class="head-info">
                <span class="name" v-show="isLogined">{{ userName }}</span>
                <span class="name" v-show="!isLogined">请登录</span>
                <span class="title">&nbsp;，欢迎进入{{liveTitle}}</span>
            </div>
        </div>

        <!-- 没有登陆就结束 -->
        <div class="m-video">
            <div :class="{'z-top': showedTopViedo && !needFakeFullScreen, 'z-full': needFakeFullScreen}"
                :style="needFakeFullScreen ? fullHeightStyle : {}"
                class="video"
                >

                <!-- 直播结束显示图 -->
                <img v-show="liveIsOver && isLogined" src="https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/1568966424047banner.png" class="live-over-show">
                <!-- <img v-show="liveIsOver" src="./../assets/banner.png" class="live-over-show"> -->

                <!-- 人脸识别提示图 -->
                <!-- <div class="disern-hint" @touchstart.stop="readDisernHint" v-show="showedDisernHint">
                    <img src="./../assets/disern-hint.png">
                </div> -->

                <!-- 播放器容器 -->
                <div :class="{'z-hide': needHideVideo}"
                    class="prism-player"
                    ref="video"
                    id="player-con"
                    :style="[bgPic ? videoBg : '']"></div>

                <!-- 直播头像/在线人数 -->
                <!-- <div class="video-info" :class="videoIsFullScreen ? 'z-fs' : ''" v-if="annoInfo!=null">
                    <img class="video-logo" :src="videoAvatar">
                    <span class="video-view" v-if="viewsNumber!=''">{{ viewsNumber }}人在线</span>
                </div> -->

                <!-- 播放器控制组件 -->
                <div v-show="showedVideoControlBar && !isOverdueHiddenVideoControlBar" class="video-controller">
                    <!-- 全屏 -->
                    <div class="video-btn"
                        :class="{'z-on': videoIsFullScreen}"
                        @touchstart.stop.prevent="shiftFullVideo"
                        @click.stop.prevent>
                        <img src="./../assets/to-full-screen.png">
                        <img src="./../assets/to-small-screen.png">
                    </div>

                    <!-- 暂停/播放 -->
                    <div class="video-btn"
                        v-show="liveInfo.liveStatus == 2"
                        :class="{'z-on': videoIsPlaying}"
                        @touchstart.stop.prevent="shiftVideoPlay"
                        @click.stop.prevent>
                        <img src="./../assets/play.png">
                        <img src="./../assets/pause.png">
                    </div>

                    <!-- 分辨率按钮横屏 -->
                    <div 
                        class="gqbtn"
                        v-show="isCrosswise && liveInfo.liveStatus != 3"
                        @touchstart.stop.prevent="shiftQualityFullScreen"
                        @click.stop.prevent>
                        <img src="../assets/shipin-big.png" alt="">
                        <span>{{qualityValue}}</span>
                    </div>
                </div>

                <!-- 分辨率按钮竖屏 -->
                <div 
                    class="video-controller videoQuality" 
                    v-show="showedVideoControlBar && !isOverdueHiddenVideoControlBar && !quality && !isCrosswise && liveInfo.liveStatus != 3"
                   >
                    <div 
                        class="gqbtn"
                        @touchstart.stop.prevent="shiftQuality"
                        @click.stop.prevent>
                        <img src="../assets/shipin-big.png" alt="">
                        <span>{{qualityValue}}</span>
                    </div>
                </div>

                <!-- 分辨率竖屏选择 -->
                <div class="chooseQuality video-controller slideInRight" v-show="quality && !isCrosswise">
                    <div class="SD">
                        <div class="huazhi"
                            @touchstart.stop.prevent="quality = false;" 
                            @click.stop.prevent>
                            <img src="../assets/shipin-small.png" alt="">
                            <span>画质</span>
                        </div>
                        <ul class="quality">
                            <li 
                                :class="{'active':thisQuality == 1}" 
                                @touchstart.stop.prevent="changeQuality(1)"
                                @click.stop.prevent>
                                <p>1080P</p>
                                <p>高清</p>
                            </li>
                            <li 
                                :class="{'active':thisQuality == 2}"
                                @touchstart.stop.prevent="changeQuality(2)"
                                @click.stop.prevent>
                                <p>720P</p>
                                <p>标清</p>
                            </li>
                            <li 
                                :class="{'active':thisQuality == 3}"
                                @touchstart.stop.prevent="changeQuality(3)"
                                @click.stop.prevent>
                                <p>480P</p>
                                <p>流畅</p>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- 分辨率横屏选择 -->
                <div class="SDFullScreen" v-show="qualityFullScreen && isCrosswise">
                    <div class="huazhi" @touchstart.stop.prevent="qualityFullScreen=false" @click.stop.prevent>
                        <img src="../assets/shipin-small.png" alt="">
                        <span>画质</span>
                    </div>
                    <ul class="quality">
                        <li 
                            :class="{'active':thisQuality == 1}" 
                            @touchstart.stop.prevent="changeQuality(1)"
                            @click.stop.prevent>
                            <p>1080P</p>
                            <p>高清</p>
                        </li>
                        <li 
                            :class="{'active':thisQuality == 2}"
                            @touchstart.stop.prevent="changeQuality(2)"
                            @click.stop.prevent>
                            <p>720P</p>
                            <p>标清</p>
                        </li>
                        <li 
                            :class="{'active':thisQuality == 3}"
                            @touchstart.stop.prevent="changeQuality(3)"
                            @click.stop.prevent>
                            <p>480P</p>
                            <p>流畅</p>
                        </li>
                    </ul>
                </div>


                <!-- 关闭页面 -->
                <div class="close-btn"
                    @touchstart.stop.prevent="closePage"
                    v-if="isAppEnv"
                    v-show="showedTopViedo &&  !needFakeFullScreen">
                    <img src="./../assets/close2.png">
                </div>

                <!-- 人脸识别模块 -->
                <div class="discern-info"  
                    onselectstart="return false" 
                    id="identifyInfo"
                    v-show="disernInfo.type != 0" 
                    v-if="allowShowDiscernBox">

                    <div class="discern-box">
                        <!-- 左侧图片部分 -->
                        <div class="img-box clear" >
                            <img :src="screenshot"
                                class="face-show"
                                ref='faceImg'
                                :class="{'z-active': disernInfo.type == 2}">
                            
                            <!-- 扫描中 -->
                            <img src="../assets/border-f.png"
                                v-show="disernInfo.type == 1"
                                class="face-border2">
                            
                            <!-- 扫描结束 人脸 -->
                            <div class="face-border z-on"
                                :style="faceBorderStyle"
                                v-show="disernInfo.type == 2 && disernInfo.disernType == 1">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                            </div>

                            <!-- 扫描结束 物品 -->
                            <div class="face-border"
                                :style="item"
                                :key="index"
                                :class="{'z-on': index==disernInfo.currGoodIndex}"
                                @touchstart.stop.prevent="selectDisernGoodIndex(index)"
                                @click.stop.prevent
                                v-for="(item, index) in goodBorderStyleArr"
                                v-show="disernInfo.type == 2 && disernInfo.disernType == 2">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                                <img src="../assets/border-corner.png">
                           </div>
                        </div>

                        <!-- 右侧文字信息部分 -->
                        <div class="text-wrap">
                            <div class="text-box" v-if="disernInfo.type == 2">
                                <div v-if="disernInfo.disernType == 1">
                                    <div class="p3">
                                        <img v-if="disernInfo.face.info.imgUrl == ''" src="../assets/avatar.png" />
                                        <img v-else :src="disernInfo.face.info.imgUrl" />

                                        <div>
                                            <img src="../assets/bg-face.png">
                                            <span>扫验成功</span>
                                        </div>
                                    </div>

                                    <p class="p4">
                                        <span>姓名：{{disernInfo.face.info.personName}}</span>
                                        <span>国籍：{{disernInfo.face.info.nationality}}</span>
                                    </p>

                                    <p class="p4">
                                        <span>简介：{{disernInfo.face.info.description}}</span>
                                    </p>

                                    <a target="_blank" :href="disernInfo.face.info.linkUrl">了解更多 >></a>
                                </div>

                                <div v-else-if="disernInfo.disernType == 2">
                                    <div class="p3">
                                        <img v-if="currDisernGood.info.imgUrl == ''" src="../assets/avatar.png" />
                                        <img v-else :src="currDisernGood.info.imgUrl" />

                                        <div>
                                            <img src="../assets/bg-face.png">
                                            <span>扫验成功</span>
                                        </div>
                                    </div>

                                    <p class="p4">
                                        <span>名称：{{currDisernGood.info.goodsName}}</span>
                                        <span>品牌：{{currDisernGood.info.brand}}</span>
                                        <span>型号：{{currDisernGood.info.model}}</span>
                                    </p>

                                    <p class="p4">简介：<span>{{currDisernGood.info.description}}</span></p>

                                    <a :href="currDisernGood.info.linkUrl">了解更多 >></a>
                                </div>
                            </div>

                            <div class="text-box" v-show="disernInfo.type == 1">
                                <p class="p1">AI小布正在识别画面中…</p>
                                <p class="p2">点击屏幕停止识别</p>
                            </div>

                            <div class="text-box" v-show="disernInfo.type == 3">
                                <p class="p1">未识别到信息</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 中间标题区域 -->
        <div class="m-box" v-show="false">
            <div class="title">
                <span class="z-stress">链群合约 生态品牌</span>
                <span>海尔920：第三届人单合一模式国际论坛</span>
            </div>
        </div>

        <!-- 侧边悬浮按钮：我要直播 -->
        <div class="TVBox" v-show="showedTVBox">
            <div :class="{'z-dim': false}">
                <img @click="showedTVBox = false" src="./../assets/close.png" class="i-close">
                <img @click="showTvbox" src="./../assets/watchTV.png" class="tv-img animated swing">
            </div>
        </div>

        <!-- 我要直播模块 -->
        <div class="TVintroduce a-fade-in" @click.self="clickTVBOx = !clickTVBOx" v-show="clickTVBOx">
            <div class="introduce">
                <img class="" src="../assets/introduce_bg.png" alt="">
                <div>
                    <img src="../assets/introduce_name.png" alt="">
                </div>
                <a href="tel:18806481128">
                    <img src="../assets/introduce_tel.png" alt="">
                </a>
            </div>
        </div>

        <!-- 聊天/了解我 -->
        <div class="content" :style="fullHeightStyle" v-show="!needFakeFullScreen">
            <div class="chat">
                <div class="nav"    :class="{'z-3': isAppEnv}">
                    <ul>
                        <li :class="{'active':show}" @click="changeStyle(1)">大家说</li>
                        <li :class="{'active':!show}" @click="changeStyle(2)">了解我</li>
                        <li class="z-stress" @click="toShare" v-show="isAppEnv">
                            <img src="./../assets/share2.png">
                            分享
                        </li>
                    </ul>
                </div>

                <div class="chatWindow" v-show="show">
                    <div class="sys clear a-fade-in-right" v-show="showSysMessage">
                        <div class="system fl">
                            <span>&nbsp;系统消息：</span>
                            <span>{{message2}}</span>加入房间
                        </div>
                    </div>

                    <div class="show" id="shows"
                        :style="fullHeightStyle"
                        :class="{'unfold': openEmoji || openPhoto}"
                        ref="ol"
                        @click="openEmoji=false;openPhoto=false">
                        
                        <ul id="ul" ref="chatList" @click="openEmoji=false;openPhoto=false">
                            <template v-for="(item, index) in chatList">
                                <!-- 对方消息: 文字 -->
                                <li v-if="(item.msgType==1 || item.msgType==2) && !item.isSelf && item.mobile!='18806481128'"
                                    v-show="!item.isDeleted"
                                    class="clear"
                                    :key = "index">
                                    <div class="ava fl"><img :src="item.avatar"></div>
                                    <div class="label fl">
                                        <div class="name" :class="{'s-office': item.msgType == 2}">
                                            {{item.nickName}}
                                            <span v-show="item.msgType == 2">官方</span>
                                        </div>
                                        <div class="cont left">
                                            <p class="message" style="word-break:break-all;" v-html="item.msg"></p>
                                        </div>
                                    </div>
                                </li>
                                <!-- 官方消息 -->
                                <li v-if="(item.mobile=='18806481128') && !item.isSelf"
                                    v-show="!item.isDeleted"
                                    class="clear"
                                    :key = "index">
                                    <div class="ava fl"><img :src="item.avatar"></div>
                                    <div class="label fl">
                                        <div class="name" :class="{'s-office': item.msgType == 2}">
                                            官方主持人（阿布）
                                            <span>官方</span>
                                        </div>
                                        <div class="cont left">
                                            <p class="message" style="word-break:break-all;" v-html="item.msg"></p>
                                        </div>
                                    </div>
                                </li>


                                <!-- 自已发送消息: 文字 -->
                                <li class="self"
                                    v-show="!item.isDeleted"
                                    :key = "index"
                                    v-else-if="(item.msgType==1 || item.msgType==2) && item.isSelf">
                                    <div class="ava">
                                        <img :src="item.avatar">
                                    </div>
                                    <div class="label">
                                        <div class="name" :class="{'s-office': item.msgType == 2}" style="text-align: right;">
                                            {{ item.nickName }}
                                            <span v-show="item.msgType == 2">官方</span>
                                        </div>
                                        <div class="cont right">
                                            <p class="message" style="word-break:break-all;" v-html="item.msg"></p>
                                        </div>
                                    </div>
                                </li>

                                <!-- 自已发送消息: 图片 -->
                                <li class="self"
                                    v-show="!item.isDeleted"
                                    :key = "index"
                                    v-else-if="item.msgType==4 && item.isSelf">
                                    <div class="ava">
                                        <img :src="item.avatar">
                                    </div>
                                    <div class="label">
                                        <div class="name" style="text-align: right;">
                                            {{ item.nickName }}
                                        </div>

                                        <img :src="item.img" @load="chatBoxScrollToBottom(true)" class="upload-pic">
                                    </div>
                                </li>

                                <!-- 对方消息: 图片 -->
                                <li v-if="item.msgType==4 && !item.isSelf && item.mobile !='18806481128'"
                                    class="clear"
                                    v-show="!item.isDeleted"
                                    :key = "index">
                                    <div class="ava fl"><img :src="item.avatar"></div>
                                    <div class="label fl">
                                        <div class="name">
                                            官方主持人（阿布）
                                            <span>官方</span>
                                        </div>

                                        <img :src="item.img" @load="chatBoxScrollToBottom(false)" class="upload-pic">
                                    </div>
                                </li>
                                <!-- 官方消息 -->
                                <li v-if="item.msgType==4 && !item.isSelf && item.mobile =='18806481128'"
                                    class="clear"
                                    v-show="!item.isDeleted"
                                    :key = "index">
                                    <div class="ava fl"><img :src="item.avatar"></div>
                                    <div class="label fl">
                                        <div class="name">
                                            {{item.nickName}}
                                        </div>

                                        <img :src="item.img" @load="chatBoxScrollToBottom(false)" class="upload-pic">
                                    </div>
                                </li>
                            </template>
                        </ul>
                    </div>
                </div>

                <div class="aboutMe" v-show="!show" ref="adoutMeRef">
                    <div class="m-info">
                        <div class="box1">
                            <img src="./../assets/al-live.png">
                        </div>
                        <p class="h2">{{liveInfo.liveName}}</p>
                        <ul class="ul1">
                            <li :style="li1">
                                <p>活动时间：{{liveInfo.beginTime}}</p>
                            </li>
                            <li :style="li3">
                                <p>主办方：{{liveInfo.sponsor}}</p>
                            </li>
                        </ul>

                        <div :class="{'z-unfold': unfold}"
                            class="activeBox"
                            ref="activ">

                            <div class="detail">
                                    <!-- 轮播图 -->
                                <div class="swiper">
                                    <swiper
                                        class="swiper-wrap"
                                        ref="mySwiper"
                                        >
                                        <swiper-slide>
                                            <img :src="liveInfo.liveImg">
                                        </swiper-slide>
                                        <!-- 常见的小圆点 -->
                                        <div class="swiper-pagination" slot="pagination"></div>
                                    </swiper>
                                </div>

                                <p>{{liveInfo.description}}</p>
                            </div>
                        </div>

                        <!-- <div class="fold" v-show="!unfold" @click="closeMore">
                            <img src="./../assets/shouqitianchong.png">
                            收起
                        </div>

                        <p class="showMore" v-show="unfold" @click="openMore">向下展开
                            <img src="./../assets/gengduo-12.png">
                        </p>   -->
                    </div>

                    <!-- <div class="m-info">
                        <div class="box3">
                            <div class="boxin">
                                <div style="display: flex">
                                    <div class="box3-l">Haier</div>
                                    <div class="box3-c">
                                        <p class="h2">青岛海尔文化产业中心</p>
                                        <li>
                                            <p class="h3" style="padding-right: 3px;">会议 8</p>
                                            <p class="h3">| 已关注 635</p>
                                        </li>
                                    </div>
                                </div>
                                <div class="box3-r">
                                    关注企业
                                </div>
                            </div>
                        </div>
                    </div> -->
                </div>
            </div>
        </div>

        <!-- 底部占位符，用于页面滚动标记 -->
        <div class="u-bottom-tag" ref="pageBottomTag"></div>

        <!-- 聊天输入 -->
        <div class="m-fm" ref="chatInputView" v-show="show && !needFakeFullScreen">
            <div class="shade" v-show="!isLogined" @click="checkLogin"></div>
            
            <div class="send clear" :class="{'z-focus': cont!=''}">
                <div class="text fl" :style="textBg">
                    <input
                        type="text"
                        id="inputId"
                        v-model="cont"
                        class="fl"
                        placeholder="快来吐槽呗～"
                        @keyup.enter="send"
                        @blur="handleInputBlur"
                        @focus="handleInputFocus">
                </div>
                <div @click="send" class="btn fr a-scale-in">发送</div>
                <img src="./../assets/more.png" class="more fr" @click="unfoldPhoto">
                <img src="./../assets/xiaomi.png"
                    class="mode fr"
                    @click="unfoldEmoji">
            </div>
            
            <div class="emoji" v-show="openEmoji">
                <ul v-show="openEmoji" class="clear">
                    <li v-for="item in picArr" :key="item.id">
                        <img :src="item.url" @click="choose(item.id)">
                    </li>
                </ul>
            </div>

            <div class="pic" v-show="openPhoto">
                <img
                    src="./../assets/pic.png"
                   
                    class="upload-pic"
                    @click="startUploadImg" >
                <span>图片</span>
                <input type="file" accept="image/*" name="asd" id="file" @change="uploadImg">
            </div>
        </div>

        <!-- 登陆模块 -->
        <div class="dialog" v-if="!isLogined" v-show="showLogin" @click.self= "closeDialog($event)" ref="dialog">
            <form class="form">
                <div class="btn-close a-fade-in" @click="closeDialog($event)"></div>

                <div class="form__cover"></div>
                <div class="form__loader">
                    <div class="spinner active">
                        <svg class="spinner__circular" viewBox="25 25 50 50">
                            <circle
                                class="spinner__path"
                                cx="50"
                                cy="50"
                                r="20"
                                fill="none"
                                stroke-width="4"
                                stroke-miterlimit="10"
                            ></circle>
                        </svg>
                    </div>
                </div>
                <div class="form__content">
                    <h1>
                        <img src="./../assets/login-title.png">
                    </h1>
                    <div class="styled-input" style="width:100%">
                        <input
                            type="number"
                            class="styled-input__input"
                            placeholder="手机号"
                            v-model="phoneNum"
                            @blur="hackBlurTop">
                        <div class="styled-input__circle"></div>
                    </div>
                    <div class="clear">
                        <div class="styled-input fl" style="width:60%">
                            <input ref="codeInput"
                                type="text"
                                class="styled-input__input"
                                placeholder="验证码"
                                @blur="hackBlurTop"
                                v-model="sysCode">
                            <div class="styled-input__circle"></div>
                        </div>

                        <div class="styled-input fr" @click="getCode" style="width:35%;">
                            <div class="code">{{ sendCodeText }}</div>
                        </div>
                    </div>
                    <!-- 密码 -->
                    <div class="styled-input" v-show="(liveType == 2 && wxLoginStatus == 2) || (liveType ==2 && !isLogined)">
						<input 
                            autocomplete="off"
							type="password" 
							class="styled-input__input" 
							placeholder="直播密码"
                            @blur="hackBlurTop"
							v-model="password">
						<div class="styled-input__circle"></div>
					</div>

                    <button type="button" class="styled-button" @click="submit">
                        <span class="styled-button__real-text-holder">
                            <span class="styled-button__real-text">Submit</span>
                            <span class="styled-button__moving-block face">
                                <span class="styled-button__text-holder">
                                    <span class="styled-button__text">登录</span>
                                </span>
                            </span>
                            <span class="styled-button__moving-block back">
                                <span class="styled-button__text-holder">
                                    <span class="styled-button__text">Submit</span>
                                </span>
                            </span>
                        </span>
                    </button>
                </div>
            </form>
        </div>
        <!-- 密码弹窗 -->
        <div class="dialog" v-show="showPassword && wxLoginStatus != 2" ref="dialogPassword">
			<form class="form">
				<div class="form__cover"></div>
				<div class="form__loader">
				  <div class="spinner active">
					<svg class="spinner__circular" viewBox="25 25 50 50">
					  <circle class="spinner__path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10"></circle>
					</svg>
				  </div>
				</div>
				<div class="form__content">
					<h1>
					    <img src="./../assets/login-title.png" alt="">
                    </h1>
                    <!-- 密码 -->
                    <div class="styled-input" v-show="liveType == 2">
						<input 
                            autocomplete="off"
							type="password" 
							class="styled-input__input" 
							placeholder="直播密码"
                            @blur="hackBlurTop"
							v-model="password">
						<div class="styled-input__circle"></div>
					</div>
					<button type="button" class="styled-button" @click="submitPassword" > <span class="styled-button__real-text-holder"> <span class="styled-button__real-text">Submit</span> <span class="styled-button__moving-block face"> <span class="styled-button__text-holder"> <span class="styled-button__text">观看</span> </span> </span><span class="styled-button__moving-block back"> <span class="styled-button__text-holder"> <span class="styled-button__text">Submit</span> </span> </span> </span> </button>
				</div>
			</form>
		</div>
    </div>
</template>

<script>
// import banner from "./../assets/banner.png";
import ingAvatar from "./../assets/ing-avatar.jpg";
import toFullScreenImg from "./../assets/to-full-screen.png";
import toSmallScreenImg from "./../assets/to-small-screen.png";
// import video from "./../assets/bb.mp4";
// import screen from "./../assets/introduce.png";
import { swiper, swiperSlide } from "vue-awesome-swiper";
import message from '../modules/message';
import html2canvas from 'html2canvas';
import conf from '../config';
require("swiper/dist/css/swiper.css");
// import Chatroom from "../../static/NIM_Web_Chatroom_v6.8.0.js";

// 阿里播放器对象
var player;

// 初始化页面高度，用于某些机型resize事件后，高度测不准问题
const iniClientHeight = window.innerHeight || document.documentElement.offsetHeight || document.body.offsetHeight;

// 获取url参数
const getQueryPara = function (paraName, dft = null) {
	var sUrl = location.href;
	var sReg = '[\?&]{1}' + paraName + '=([^&]*)';
	var re = new RegExp(sReg);
	var rst = (sUrl.match(re));
	if (rst === null) return dft;
	return decodeURIComponent(rst[1]);
};

/**
 * 安全范围
 * 假设球在从0到10的线上运动，球本身直接2米，那球中心就只能在1-9的范围内运动，无法逾越
 */
function getSafeScope(allScope, radius, inputValue){
    let min = radius,
        max = allScope - radius;
    return inputValue>max ? max : (inputValue<min ? min : inputValue);
}

// 获取浏览器版本及语言
const browser = {
	// 版本
	versions: function() {
		const u = navigator.userAgent;
		return { //移动终端浏览器版本信息
			trident: u.indexOf('Trident') > -1, //IE内核
			presto: u.indexOf('Presto') > -1, //opera内核
			webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
			gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
			mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
			iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
			iPad: u.indexOf('iPad') > -1, //是否iPad
			weixin: u.indexOf('MicroMessenger') > -1, //是否微信
			webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
		};
	}(),
	// 语言
	language: (navigator.browserLanguage || navigator.language).toLowerCase()
};

const isIosAllScreen = (()=>{
    const width = window.screen.width,
        height = window.screen.height;
    return (width==375 && height==812)
        || (width==414 && height==896);
})();


export default {
    name:"index",

    data(){
        const that = this;
        return{
            liveTitle: "正在发布",
            // 干嘛用的？
            waggle:true,

            videoPlayer:"",//播放器初始化

            // 人脸识别模块
            screenshot:"",//截图信息
            backInfo:"",//oss上传返回信息
            
            // 图像识别结果内容
            disernInfo:{
                type: 0, //识别状态 0未开始 1进行中 2成功 3失败

                disernType: 1, // 1人脸 2物品

                // 截图宽高
                srcImgWidth: 300,
                srcImgHeight: 300,

                // 人脸模块
                face: {
                    info: {
                        imgUrl: '',
                        personName: '**',
                        partisan: '**',
                        description: '**',
                    },

                    Rect: {
                        Top: 0,
                        Left: 0,
                        width: 0,
                        Height: 0,
                    }
                },

                // 多个商品情况下，当前显示
                currGoodIndex: 0,
                // 物品模块
                good: [
                    // {
                    //     info: {
                    //         imgUrl: '',
                    //         goodsName: '**',
                    //         brand: '**',
                    //         model: '**',
                    //         description: '**',
                    //     },

                    //     rect: {
                    //         top: 0,
                    //         left: 0,
                    //         width: 200,
                    //         height: 100,
                    //     }
                    // }, {
                    //     info: {
                    //         imgUrl: '',
                    //         goodsName: '****',
                    //         brand: '****',
                    //         model: '****',
                    //         description: '****',
                    //     },

                    //     rect: {
                    //         top: 50,
                    //         left: 50,
                    //         width: 80,
                    //         height: 100,
                    //     }
                    // }
                ]
            },

            //画质改变
            thisQuality:1,
            quality:false,
            qualityFullScreen:false,
            qualityValue:"高清",
            allSource:"",

            // 干嘛用的？
            onLink:false,

            //播放器设置
            playState:true,//默认直播
            fullDelete:true,
            videoSource2: "",

            // 聊天默认头像
            defaultAva: require("./../assets/defaultPic.png"),
            // 聊天默认官方头像
            defaultOfficialAva: require("./../assets/avatar.png"),

            //背景图片20191213
            webBg:{
                backgroundImage:"url('https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/1576115619622_bg.jpg')",
            },
            //背景图片通用
            // webBg:{
            //     backgroundImage:"url(https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/beijing.png)",
            // },
            // contentBg:{
            //     backgroundImage:"url(" + require("../assets/bg-font.png") + ")" ,
            // },
            textBg:{
                backgroundImage:"url(" + require("../assets/talk.png") + ")" ,
            },
            li1:{
                backgroundImage:"url(" + require("../assets/shijian.png") + ")" ,
            },
            li2:{
                backgroundImage:"url(" + require("../assets/zhiyuandidian7.png") + ")" ,
            },
            li3:{
                backgroundImage:"url(" + require("../assets/gongsi.png") + ")" ,
            },
            fontFace:{
                backgroundImage:"url(" + require("../assets/bg-face.png") + ")" ,
            },
            videoBg:{
                backgroundImage:"url(https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/1568966424047banner.png)" ,
            },
            bgPic:true,
            // 用户信息
            userName: window.localStorage.userName || "",
            img: window.localStorage.img || this.defaultAva,
            token:window.localStorage.token || "",

            // 干啥用的？
            position: "20%",

            // 显示聊天还是了解我，用这个字段命名合理吗？但是我懒得改了
            show:true,

            // 聊天输入内容
            cont:"",

            // 聊天 websocket
            wst:null,

            // 干嘛用的？
            client:{},

            // 聊天消息容器？反正我没用
            value:[],   //消息容器

            // 显示表情模块
            openEmoji:false,

            // 显示上传图片模块
            openPhoto:false,

            // 表情数组，用emojiArr命名会不会更好？
            picArr:[
                {
                    id:1,
                    url:require('./../assets/emoji/daxiao@2x.png'),
                    icon:"[大笑]"
                },
                {
                    id:2,
                    url:require('./../assets/emoji/mianwubiaoqing@2x.png'),
                    icon:"[面瘫]"
                },
                {
                    id:3,
                    url:require('./../assets/emoji/ganga@2x.png'),
                    icon:"[尴尬]"
                },
                {
                    id:4,
                    url:require('./../assets/emoji/xiaochulei@2x.png'),
                    icon:"[笑哭]"
                },
                {
                    id:5,
                    url:require('./../assets/emoji/feiwen@2x.png'),
                    icon:"[飞吻]"
                },
                {
                    id:6,
                    url:require('./../assets/emoji/yun-2@2x.png'),
                    icon:"[晕]"
                },   
                {
                    id:7,
                    url:require('./../assets/emoji/bizui@2x.png'),
                    icon:"[闭嘴]"
                },
                {
                    id:8,
                    url:require('./../assets/emoji/ziya@2x.png'),
                    icon:"[呲牙]"
                },
                {
                    id:9,
                    url:require('./../assets/emoji/ku@2x.png'),
                    icon:"[酷]"
                },
                {
                    id:10,
                    url:require('./../assets/emoji/liulei@2x.png'),
                    icon:"[流泪]"
                },
                {
                    id:11,
                    url:require('./../assets/emoji/shuizhuo@2x.png'),
                    icon:"[睡觉]"
                },
                {
                    id:12,
                    url:require('./../assets/emoji/shimo@2x.png'),
                    icon:"[害怕]"
                },
                {
                    id:13,
                    url:require('./../assets/emoji/heng@2x.png'),
                    icon:"[哼]"
                },
                {
                    id:14,
                    url:require('./../assets/emoji/liubixie@2x.png'),
                    icon:"[鼻血]"
                },
                {
                    id:15,
                    url:require('./../assets/emoji/santiaoxian@2x.png'),
                    icon:"[汗]"
                },
                {
                    id:16,
                    url:require('./../assets/emoji/yiwen@2x.png'),
                    icon:"[疑问]"
                },
                {
                    id:17,
                    url:require('./../assets/emoji/xingxingyan@2x.png'),
                    icon:"[星星]"
                },
                {
                    id:18,
                    url:require('./../assets/emoji/tiaopi@2x.png'),
                    icon:"[调皮]"
                },
                {
                    id:19,
                    url:require('./../assets/emoji/biti@2x.png'),
                    icon:"[鼻涕]"
                },
                {
                    id:20,
                    url:require('./../assets/emoji/xinsui@2x.png'),
                    icon:"[心碎]"
                },
                {
                    id:21,
                    url:require('./../assets/emoji/aixin-4@2x.png'),
                    
                    icon:"[爱心]"
                },
                {
                    id:22,
                    url:require('./../assets/emoji/zhadan@2x.png'),
                    icon:"[炸弹]"
                },
                {
                    id:23,
                    url:require('./../assets/emoji/shuai@2x.png'),
                    icon:"[衰]"
                },
            ],

            // 干嘛用的？
            id:1,
            isChoose1:true,
            isChoose2:false,
            isChoose3:false,

            // 干嘛用的？向下展开？
            unfold:true,
            // 干嘛用的？
            heightRecord:"",    
            // 干嘛用的？
            aboutMeScroll:"",

            showSysMessage:false,  //显示系统消息
            message :{},    //websocket获得消息
            message1 :"",   //系统消息分割
            message2 :"",   //系统消息分割

            showLogin:false,  //展示登录
            showPassword:false,  //展示密码框

            phoneNum:"",//手机号
            sysCode:"", //验证码
            password:"",//密码
            liveType: "",// 1普通 2密码

            liveInfo:{},//直播详情
            annoInfo:{},//直播信息
            annoXqInfo:[],//直播详情
            annoLcInfo:[],//活动流程
            annoJbInfo:[],//活动嘉宾
            liveList:[],//直播列表

            videoSource:window.sessionStorage.source ? window.sessionStorage.source : "",//播放源
            streamId: "",
            userId:window.localStorage.Id,
            type: 1,//0是回看 1是直播

            // 已经获取直播
            isGetedLive: false,

            // 是否点击了”我要直播“按钮，命名是否合理？
            clickTVBOx:false,

            // 显示我要直播模块
            showedTVBox: true,

            // 轮播图模块
            imgIndex: 1,
            swiperOption: {//是一个组件自有属性，如果notNextTick设置为true，组件则不会通过NextTick来实例化swiper，也就意味着你可以在第一时间获取到swiper对象，假如你需要刚加载遍使用获取swiper对象来做什么事，那么这个属性一定要是true
                notNextTick: true,//循环
                loop: true,//设定初始化时slide的索引
                initialSlide: 0,//自动播放
                autoplay: {
                    delay: 1500,
                    stopOnLastSlide: false,/* 触摸滑动后是否继续轮播 */
                    disableOnInteraction: false
                },
                speed: 800,//滑动速度
                direction: "horizontal",//滑动方向
                grabCursor: true,//小手掌抓取滑动
                on: {
                    slideChangeTransitionStart: function() {//滑动之后回调函数
                        that.imgIndex= this.realIndex - 1; /* realIndex为滚动到当前的slide索引值 */
                    },
                },
                pagination: {//分页器设置
                    el: ".swiper-pagination",
                    clickable: true,
                    type: "bullets"
                }
            },
            imgName:"",

            // 是否悬浮置顶播放器
            showedTopViedo: false,

            //是否已登录
            isLogined: false,

            // 是否是原生app环境
            isAppEnv: (typeof window.webkit != 'undefined' && typeof window.webkit.messageHandlers != 'undefined' && typeof window.webkit.messageHandlers.Goshare != 'undefined') || typeof window.JsInterface !='undefined',
            isAndAppEnv: typeof window.JsInterface !='undefined',
            isIosAppEnv: (typeof window.webkit != 'undefined' && typeof window.webkit.messageHandlers != 'undefined' && typeof window.webkit.messageHandlers.Goshare != 'undefined'),

            // 上次点击video时间，用来模拟双击
            lastClickVideoTime: 0,

            // 聊天输入框是否聚焦
            chatInputIsFocused: false,

            // ws初次加载记录
            wstFirstLoaded: false,

            // 视频是否全屏
            videoIsFullScreen: false,

            // 观看人数
            viewsNumber: '',

            // 横竖屏状态检测
            isCrosswise: false,

            // 侧边悬浮框是否隐藏
            tvboxIsDim: false,

            // 发送短信相关
            sendCodeData: {
                status: 1, // 1初始发送，2正在发送，3重新发送，4发送成功尚未转完cd
                cd: 60
            },

            // 已阅人脸识别操作提示
            haveReadDisernHint: false,

            // 已经开始播放了
            videoIsFirstPlayed: false,

            // 聊天窗口上次是否在底部
            chatBoxLastTimeIsAtBottom: true,

            // 显示播放器控制台
            showedVideoControlBar: false,

            // 上次单击video时间
            lastClickVideoTimeForBar: 0,

            // 显示5s后隐藏控制栏
            isOverdueHiddenVideoControlBar: false,

            // 正在播放
            videoIsPlaying: false,

            // 页面实时高度
            clientHeight: iniClientHeight,

            // 微信登陆相关
            isWxEnv: navigator.userAgent.indexOf('MicroMessenger') > -1, //是否微信环境
            wxLoginCode: getQueryPara('code'), //微信登陆返回code
            wxLoginState: getQueryPara('state'), //微信返回state, 默认zzfb
            wxOpenId: '',
            wxUnionId: '',
            wxBindPhoneStatus: 0, // 微信未绑定手机号 0未知 1已绑定 2未绑定
            wxLoginStatus: 0, // 微信登陆状态 是否成功 0未开始 1进行中 2成功 3失败

            // 直播id
            liveId: '',

            // 直播已结束
            liveIsOver: false,
            
            chatroomId: "",//聊天室Id
            chatroom: {},//聊天实例
            // 聊天列表
            chatList: [
                {
                    id: 0,
                    nickName: '官方主持人（阿布）',
                    avatar: require("./../assets/avatar.png"),
                    msgType: 2,
                    msg: '欢迎您进入本场直播，您可以在此发表您的评论。（不要发送低俗、反动、色情等言论）！',
                    img: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1567228967120&di=66f584f5df494a59352e448a6df2e8ad&imgtype=0&src=http%3A%2F%2Fpic33.nipic.com%2F20131007%2F13639685_123501617185_2.jpg',
                    isSelf: false,
                    isDeleted: false,
                }
            ],
            baseImgUrl: "https://app.ailive.cloud/app",

            // 微信分享信息 
            shareInfo: {
                title: '',
                url: '',
                img: '',
                content: '',
            },
            showSysMessageTimer: {},
        }
    },

    watch: {

        // 干嘛用的？
        onLink(val){
            console.log( val);
            this.linkWebket();
        },

        // 干嘛用的？
        chatScroll(val){
            var ul = document.getElementById('ul');
            console.log(val,ul.offsetHeight)
        },

        // 这函数有什么意义？
        cont(val){
            val=val.replace(/(^\s*)/g, "");
        },

        // 视频是否全屏
        videoIsFullScreen(val){
            if(val){
            }
        },

        // 是否显示人脸识别提示
        showedDisernHint(val){
            if(val){
                setTimeout(()=>{
                    this.readDisernHint();
                }, 5000);
            }
        },
        // 监听图片上传完成发送消息
        imgName(val){
            if(val){
                this.wst.send("img::" + val);
                console.log('ws发送图片：' + val);
            }
        },
        chatList(newVal, oldVal){
            this.$nextTick(()=>{
                var scrollTop = 0;
                if((this.$refs.chatList.offsetHeight+300) > document.getElementById("shows").offsetHeight){
                    scrollTop = (this.$refs.chatList.offsetHeight+300) - document.getElementById("shows").offsetHeight
                    console.log(scrollTop)
                }
                document.getElementById("shows").scrollTop = scrollTop;
            });
        },
    },

    computed: {
        videoPlayState(){
            if(this.videoPlayer){
                return this.videoPlayer.getStatus();
            }else{
                return '';
            }
        },

        // 满屏高度样式，替代100vh，以达到随浏览器高度实时变化
        fullHeightStyle(){
            return {
                height: this.clientHeight + 'px'
            };
        },

        // 需要隐藏播放器，在有弹窗蒙版情况下
        needHideVideo(){
            return this.showLogin || this.clickTVBOx;
        },

        // 需要伪全屏
        needFakeFullScreen(){
            return this.isCrosswise || this.videoIsFullScreen;
        },

        // 允许显示人脸识别模块
        allowShowDiscernBox(){
            return this.isCrosswise;
        },

        // 发送手机验证码按钮显示文字
        sendCodeText() {
			switch (this.sendCodeData.status) {
			case 1:
				return '获取验证码';
			case 2:
				return '发送中……';
			case 4:
				return '重新获取' + this.sendCodeData.cd + '\'';
			case 3:
				return '重新获取';
			}
        },
        
        // 人脸框位置
        faceBorderStyle (){
            const {disernInfo:{type, disernType, srcImgWidth, srcImgHeight, face:{Rect}}} = this;
            if(type != 2 || disernType!=1){
                return {};
            } else {
                let res = {
                    left: (Rect.Left * 100 / srcImgWidth) + '%',
                    width: (Rect.Width * 100 / srcImgWidth) + '%',
                    top: (Rect.Top * 100 / srcImgHeight) + '%',
                    height: (Rect.Height * 100 / srcImgHeight) + '%',
                };
                console.log(res, Rect);
                return res;
            }
        },

        // 物品框位置
        goodBorderStyleArr (){
            const {disernInfo:{type, disernType, srcImgWidth, srcImgHeight, good}} = this;
            if(type!=2 || disernType!=2 || good.length <= 0){
                return [];
            } else {
                return good.map(item => {
                    let res = {
                        left: (item.rect.left * 100 / srcImgWidth) + '%',
                        width: (item.rect.width * 100 / srcImgWidth) + '%',
                        top: (item.rect.top * 100 / srcImgHeight) + '%',
                        height: (item.rect.height * 100 / srcImgHeight) + '%',
                    };
                    console.log(res, item);
                    return res;
                });
            }
        },

        // 聊天输入框样式
        chatInputStyle(){
            const { chatInputIsFocused } = this;
            if(browser.versions.ios && !isIosAllScreen) {
                if(chatInputIsFocused) {
                    return {
                        'position': 'static'
                    };
                } else {
                    return {
                        'position': 'fixed'
                    };
                }
            } else {
                return {};
            }
        },

        // 是否显示人脸识别截图 
        showedDisernHint(){
            return !this.haveReadDisernHint && this.isCrosswise && this.videoIsFirstPlayed;
        },

        // 当前识别物品
        currDisernGood(){
            const {disernInfo:{type, currGoodIndex, good}} = this;
            if(good.length > 0){
                return good[ currGoodIndex ];
            }
        },

        // 用户头像
        userAvatar(){
            const {img, defaultAva, isLogined} = this;
            if(!isLogined) {
                return defaultAva;
            } else {
                if(img=='' || img=='/img/default_main_pic.png') {
                    return defaultAva;
                } else {
                    return img;
                }
            }
        },

        // 视频logo头像
        videoAvatar(){
            return (this.annoInfo&& typeof this.annoInfo.logoUrl=='string' && this.annoInfo.logoUrl!='') ? this.annoInfo.logoUrl : ingAvatar;
        },

        //图片与文字拼接
        ReCont() {
            return function(strCont){
                // console.log(strCont)
                if(strCont == ""){
                    return
                }
                for (var i in this.picArr) {        
                    var item = this.picArr[i];
                    var strimg=" <img src="+item.url+">";
                    var reg=new RegExp("\\"+item.icon,"g");
                    // alert(reg);
                    // console.log(item.url)
                    strCont=strCont.replace(reg, strimg);
                    //alert(strCont);
                }    
                return strCont;
            }
        },
        // 处理默认头像
        acquiescehead(){
            return function(url){
                if(url == "/img/default_main_pic.png"){
                    return "https://app.ailive.cloud/app/img/default_main_pic.png"
                }else{
                    return url
                }
            }
        },
        // 时间戳转化
        getTimeStr(){
            return function(str){
                if(!str){
                    return
                }
                var num = parseInt(str);
                var time = new Date(num);
                var year = time.getFullYear();
                var month = time.getMonth() + 1;
                var date = time.getDate();
                var hours = time.getHours();
                var minutes = time.getMinutes();
                if(month < 10){
                    month = "0" + month
                }
                if(date < 10){
                    date = "0" + date
                }
                if(hours < 10){
                    hours = "0" + hours
                }
                if(minutes < 10){
                    minutes = "0" + minutes
                }
                return year + "-" +　month + "-" + date + "    " + hours + ":" + minutes
            }
        },
    },

    components: {
        swiper,
        swiperSlide
    },

    created() {
        // 直播id初始化
        let streamId = getQueryPara('streamId');
        if(typeof streamId=='string'){
            if(streamId.indexOf('#') != -1){
                streamId = streamId.split('#')[0];
            }
            this.streamId = streamId || '';
        }

        // app环境初始化
        this.uriIni();

        // 获取流信息
        this.getInfo();

        this.initialize();
        
        window.setInterval(() => {
            this.initialize();
            console.log("初始化oss")
            // window.clearInterval(this.timer);
        },3500000)

        // 如果已登陆，初始化
        if(this.token){
            this.isLogined = true;
        }

        // 监听滚动
        window.addEventListener('scroll', () => {
			let t = document.documentElement.scrollTop || document.body.scrollTop;
			if (typeof this.handleWindowScroll == 'function') {
				this.handleWindowScroll(t);
			}
        });

        // 监听屏幕变化
        window.addEventListener('resize', () => {
            this.doCheckResize();
        });

        // 定时任务
        setInterval(()=>{
            // 输入框bug
            if(this.chatInputIsFocused){
                if(typeof this.$refs.chatInputView.scrollIntoViewIfNeeded=='function'){
                    this.$refs.chatInputView.scrollIntoViewIfNeeded();
                } else {
                    this.$refs.chatInputView.scrollIntoView();
                }
                if(browser.versions.ios && !isIosAllScreen){
                    // let doc = document.documentElement || document.body;
                    // let st = doc.scrollHeight - doc.clientHeight;
                    // console.log(st);
                    // window.scrollTo(0, st);
                    window.scrollTo(0, 10000);
                }
            }

            // 监听播放状态，始终播放
            this.listenPlayStatus();
        }, 500);

        // 横竖屏状态检测
        this.checkResize();

        // 微信环境初始化
        // this.wxEnvIni();
        if(window.sessionStorage.getItem("wxLoginInfo")){
            this.wxLoginStatus = 2;
            this.wxUserLogin();
        }else{
            this.wxLogin();
        }
    },
    methods: {
        // 控制栏显示5s后隐藏
        overdueHiddenVideoControlBar(){
            this.isOverdueHiddenVideoControlBar = false;
            let lastClickVideoTimeForBar = new Date().getTime();
            this.lastClickVideoTimeForBar = lastClickVideoTimeForBar;

            setTimeout(()=>{
                if(lastClickVideoTimeForBar == this.lastClickVideoTimeForBar && this.videoIsPlaying){
                    this.isOverdueHiddenVideoControlBar = true;
                }
            }, 5000);
        },

        // 监听页面滚动
        handleWindowScroll(t){
            this.hideTvbox();
            // 判断高度固定播放器位置
			if(t > px2px(300)){
                this.showedTopViedo = true;
            } else {
                this.showedTopViedo = false;
            }
        },

        // 输入框聚焦
        handleInputFocus(){
            this.openEmoji = false;
            this.openPhoto = false;
            this.chatInputIsFocused = true;

            if(browser.versions.ios){
                // window.scrollTo(0, 0);
            }
        },

        // 聊天输入框失去焦点
        handleInputBlur(){
            this.openEmoji = false;
            this.openPhoto = false;
            this.chatInputIsFocused = false;

            this.$nextTick(()=>{
                this.hackBlur();
            });
        },

        //获取直播详情
        async getInfo(){
            let { streamId } = this;
            if(streamId.indexOf("?") != -1){
                let arr = streamId.split("?");
                streamId = arr[0];
            }
            const res = await this.$http.get("/api/queryDetailByStreamId", {
                params:{
                    streamId,
                    type: '直播',
                }
            });

            if(res.data.code == 0 && res.data.liveInfo!=null){
                // window.localStorage.streamId = res.data.liveInfo.liveStreamId;
                // this.streamId = res.data.liveInfo.liveStreamId;
                this.livePassword = res.data.liveInfo.livePassword;
                // this.livePassword = "2";
                this.liveType = res.data.liveInfo.liveType;
                if(this.liveType == 2 && window.sessionStorage.getItem("password") != this.livePassword){
                    if(this.isLogined){
                        this.openPassword();
                    }else{
                        this.openLogin();
                    }
                }
                this.chatroomId = res.data.liveInfo.roomId;
                // 微信分享信息
                this.shareInfo = {
                    title: res.data.liveInfo.wechatTitle,
                    url: res.data.liveInfo.wechatLinkUrl,
                    img: res.data.liveInfo.wechatImgUrl,
                    content: res.data.liveInfo.wechatContent,
                };

                if(res.body.annoInfo){
                    this.annoInfo = res.body.annoInfo;
                    this.annoInfo.actTags = res.body.annoInfo.actTags.split(',');
                }
                this.liveInfo = res.body.liveInfo;
                this.annoXqInfo = res.body.annoXqInfo;
                this.annoLcInfo = res.body.annoLcInfo;
                this.annoJbInfo = res.body.annoJbInfo;
                this.liveList = res.body.xgtjlist;
                this.liveTitle = this.liveInfo.title;
                document.title = this.liveTitle;

                if(window.localStorage.getItem("token") && window.localStorage.getItem("user")){
                    this.linkWebket();
                }
                this.visiterAdd();
                if(this.liveInfo.liveStatus == 3){
                    this.videoSource2 = res.data.playList[0]
                    this.iniVideo();
                }else{
                    this.getLive();
                }
            } else {
                
            }
        },
        
        //直播拉流
        getLive(){
            if(this.isGetedLive) return;
            if(this.streamId.indexOf("?") != -1){
                let arr = this.streamId.split("?");
                this.streamId = arr[0];
            }
            this.$http.post("/api/createPullUrl?streamId=" + this.streamId + "&type=" + this.type)
            .then((res) => {
                if(res.data.code == 500){
                    return message.warning(res.data.msg)
                }
                // console.log(res)
                if(res.data.URL){
                    window.sessionStorage.source = res.data.URL;
                    this.allSource = res.data.URL;
                    // this.videoSource = this.allSource.m3u8_lsd.replace("http:","")
                    this.videoSource = res.data.URL.m3u8.replace("http:","");
                    this.isGetedLive = true;
                    this.$nextTick(() => {
                        // if(){

                            this.iniVideo();
                        // }
                    })
                }
            }).catch((error) => {
                console.log(error)
            });
        },

        // 初始化播放器
        iniVideo(){
            // console.log(this.videoSource)
            var that = this;
            player = new Aliplayer({
                "id": "player-con",
                "source": that.liveInfo.liveStatus == 2 ? that.videoSource : that.videoSource2.playUrl,
                // "source":"http://vod.ailive.cloud/liveRecord/77bd17852bce890292935dba4d4483b5/ai-live/6e1a9fcb41174902ba8433e32d86e1a9/2019-11-15-08-29-44_2019-11-15-12-14-51.m3u8",
                "width": "100%",
                "height": "100%",
                "autoplay":false,
                "isLive": that.liveInfo.liveStatus == 2 ? true : false,
                // "isLive": false,
                "playsinline": true,
                "preload": true,
                "showBuffer":true,
                "controlBarVisibility": "click",
                "useH5Prism": true,
                "extraInfo":{
                    "crossOrigin":"anonymous",
                    "liveRetry":1,
                },
                "cover":"https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/1568966424047banner.png",
            }, function (player) {
                console.log("The player is created");
                that.bgPic = false;
                player.on('error', ()=>{
                    that.liveIsOver = true;
                    that.bgPic = true;
                });

                player.on('liveStreamStop', ()=>{
                    // this.liveIsOver = true;
                });

                player.on('canplay', ()=>{
                    that.liveIsOver = false;
                });
                

                player.on('showBar', ()=>{
                    // player.getComponent('fakeFullScreen').$html.style.display = 'block';
                    that.showedVideoControlBar = true;
                    that.overdueHiddenVideoControlBar();
                });

                player.on('hideBar', ()=>{
                    that.showedVideoControlBar = false;
                    that.quality = false;
                    that.qualityFullScreen = false;
                    // console.log("隐藏")
                });

                player.on('ready', ()=>{
                    that.overdueHiddenVideoControlBar();
                });
            });
            this.videoPlayer = player;
        },


        //退出
        logout(){
            if(confirm("确认退出登陆？")) {
                localStorage.removeItem("token");
                localStorage.removeItem("user");
                location.reload();
            }
        },
        // 软退出
        softLogout(){
            localStorage.removeItem("token");
            localStorage.removeItem("user");
        },
        
        // 全屏监听
        fullScreen(e){
            console.log("我全屏啦");
            // this.videoIsFullScreen = true;
            this.doCheckResize();
        },

        // 小屏继续播放
        SmallScreen(player){
            // 小屏后继续播放
            player.play();
            this.doCheckResize();
        },
        // DataURL转Blob对象
        dataURLToBlob(dataurl){
            var arr = dataurl.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        },

        //聊天初始化
        linkWebket(){
            var that = this;
            if('WebSocket' in window && window.localStorage.token) {
                
            console.log("开始链结")
             const baseUrl = process.env.NODE_ENV=='production' ? 'wss://app.ailive.cloud' : 'wss://test.ailive.cloud';
                this.wst = new WebSocket(baseUrl + "/websocket/ws/" +  this.streamId + "/" + window.localStorage.token);

                if(!this.wstFirstLoaded){
                    this.wst.onopen = function(){
                        console.log("恭喜你！ws连接成功");
                    }

                    this.wst.onclose = (err) => {
                        console.log("ws意外关闭：onerror", err)               

                        setTimeout(()=>{
                            // this.linkWebket();
                        }, 10000);
                        
                        // if(confirm('连接已断开，确认重连')){
                        // }
                    }
                } else {
                    this.wstFirstLoaded = true;
                }
                
                this.wst.onmessage = function(evt) {
                    let revMsg;
                    try {
                        revMsg = JSON.parse(evt.data);
                    } catch(e) {
                        return console.log('ws消息格式错误', evt.data);
                    }
                    that.message = revMsg;
                    console.log(that.message)
                    //获取系统消息
                    if(revMsg.system && revMsg.msgType == 3 && revMsg.nickName!= "官方主持人（阿布）"){
                        that.showSysMessage = true;
                        revMsg.message.split(':');
                        that.message1 = revMsg.message.split(':')[0];
                        that.message2 = revMsg.message.split(':')[1].replace("加入房间","").replace(")","");
                        window.clearInterval(that.showSysMessageTimer);
                        that.showSysMessageTimer = window.setInterval(function(){
                            that.showSysMessage = false;
                            window.clearInterval(that.showSysMessageTimer);
                        }, 1500);
                    } else {//获取别人消息
                        that.chatBoxLastTimeIsAtBottom = that.$refs.ol.scrollTop >= (that.$refs.chatList.offsetHeight + px2px(250) - that.$refs.ol.offsetHeight);

                        if(revMsg.icon == "/img/default_main_pic.png"){
                            revMsg.icon = '';
                        }
                        if(revMsg.msgType == 1 || revMsg.msgType == 2){ // 文字信息
                            that.receiveTextMsg(revMsg.msgType, revMsg.nickName, revMsg.icon, revMsg.message, revMsg.messageId, revMsg.mobile);
                        } else if(revMsg.msgType == 4){ // 图像信息
                            that.receiveImgMsg(revMsg.nickName, revMsg.icon, revMsg.message, revMsg.messageId);
                        } else if (revMsg.msgType == 6){ // 当前观看人数：
                            that.viewsNumber = revMsg.message;
                            console.log('当前观看人数：', that.viewsNumber);    
                        }else if(revMsg.msgType == 5) { // 删除消息
                            that.delChatMsg(revMsg.messageId);
                        } else {
                            return;
                        }
                    }
                }
            }
            else{
                // alert('Not support websocket')
            }
        },
        //发送文字消息
        send(){
            if(!this.cont){
                return message.error('发送内容不能为空', 1200);
            }

            this.wst.send(this.cont);

            let item = {
                nickName: this.userName,
                avatar: JSON.parse(window.localStorage.getItem("user")).img || this.defaultAva,
                msgType: 1,
                msg: '',
                img: '',
                isSelf: true,
                isDeleted: false,
            };

            if(this.message.publisher){
                item.msgType = 3;
            }
            item.msg = this.ReCont(this.cont);
            this.chatList.push(item);

            // 清空文字
            this.cont = "";

            this.$nextTick(() => {
                this.openEmoji = false;
                this.openPhoto = false;
                document.getElementById('inputId').blur();
                this.chatBoxScrollToBottom();
            });
        },
        //发送图片消息
        sendImgMsg(img = ''){
            if(img == ''){
                return message.error('图片为空', 1200);
            }

            let item = {
                nickName: this.userName,
                avatar: JSON.parse(window.localStorage.getItem("user")).img || this.defaultAva,
                msgType: 4,
                msg: '',
                img,
                isSelf: true,
                isDeleted: false,
            };

            this.chatList.push(item);

            console.log(item);

            this.$nextTick(() => {
                this.openEmoji = false;
                this.openPhoto = false;
                this.chatBoxScrollToBottom();
            });
        },

        // 收到图片消息
        receiveImgMsg(nickName='', icon='', img='', messageId=0){
            if(img == ''){
                return message.error('图片为空', 1200);
            }

            let item = {
                messageId,
                nickName,
                avatar: icon || this.defaultAva,
                msgType: 4,
                msg: '',
                img,
                isSelf: false,
                isDeleted: false,
            };

            this.chatList.push(item);

            this.$nextTick(() => {
                this.chatBoxScrollToBottom(false);
            });
        },

        // 收到文字消息
        receiveTextMsg(msgType, nickName='', icon='', msg='', messageId=0, mobile=''){
            if(msg == ''){
                return message.error('图片为空', 1200);
            } else {
                msg = this.ReCont(msg);
            }

            let item = {
                messageId,
                nickName,
                avatar: icon || (msgType==2 ? this.defaultOfficialAva : this.defaultAva),
                msgType,
                msg,
                img: '',
                mobile,
                isSelf: false,
                isDeleted: false,
            };

            this.chatList.push(item);

            this.$nextTick(() => {
                // this.chatBoxScrollToBottom(false);
            });
        },
        // 删除聊天消息
        delChatMsg(id){
            this.chatList.forEach(item => {
                if(item.id == id){
                    item.isDeleted = true;
                }
            });
        },

        // 开始上传图片
        startUploadImg(){
            var file = document.getElementById("file");
            file.click();
        },
        //http请求
        uploadImg(){
            var that = this;
            let tempCheckpoint;
            var file = document.getElementById("file").files[0];
            var reads = new FileReader();
            reads.readAsDataURL(file);
            reads.onload = function(e) {
                that.sendImgMsg(this.result);
            };

            this.openPhoto = false;
            console.log(file);

            if(this.client.put){
                this.client.put(file.name, file, { 
                    progress: async function (p, checkpoint) {
                        // 断点记录点。 浏览器重启后无法直接继续上传，需用户手动触发进行设置。
                        tempCheckpoint = checkpoint;
                    },
                }).then((res) => {
                    console.log('图片上传成功: ', res);
                    this.imgName = file.name;
                }).catch((err) => {
                    message.error('图片上传失败!');
                    console.error('上传oss出错', err);
                });
            }else{
                this.initialize();
                // this.uploadImg();
            }
        },
        
        changeStyle(val){
            if(val == 1){
                this.show = true;
                this.position = '20%';
            }
            if(val == 2){
                this.show = false;
                this.position = '70%';
                this.$nextTick(() => {
                    this.heightRecord = this.$refs.activ.offsetHeight;
                })
            }
        },
        openPassword(){
            this.showPassword = true;
            setTimeout(function () {
                document.body.classList.add('on-start');
            }, 100);
            
            setTimeout(function () {
                document.body.classList.add('document-loaded');
            }, 500);
        },

        // 切换登陆
        shiftLogin(){
            if(this.isLogined) {
                if(!this.isAppEnv){
                    this.logout();
                }
            } else {
                this.openLogin();
            }
        },

        // 打开登陆模块
        openLogin(){
            this.showLogin = true;
            setTimeout(function () {
                document.body.classList.add('on-start');
            }, 100);
            
            setTimeout(function () {
                document.body.classList.add('document-loaded');
            }, 200);
        },

        //获取焦点检查登录状态
        checkLogin(){
            console.log(1111)
            if(this.liveType == 2 && !this.isLogined){
                if(!this.token){
                    message.error('请登录后发言', 1200);
                    this.openLogin();
                    return
                }else{
                    //消息提示
                    message.error('请输入直播密码', 1200);
                    //弹出登录密码
                    this.openPassword();
                }
            }
        },
        checkChat(){
            if(!this.token){
                message.error('请登录后发言', 1200);
                this.openLogin();
                return
            }
        },


        unfoldEmoji(){
            document.getElementById('inputId').blur();
            this.openEmoji=!this.openEmoji;
            if(this.openEmoji){
                this.openPhoto = false;
            }
        },

        unfoldPhoto(){
            document.getElementById('inputId').blur();
            this.openPhoto = !this.openPhoto;
            if(this.openPhoto){
                this.openEmoji = false;
            }
        },
        choose(id){
            // console.log(id)
            var newObj = this.picArr.filter((item) => {
                return item.id == id
            })
            this.cont += newObj[0].icon;
            // document.getElementById('inputId').focus()
        },
        isActive(val){
            if(val == 1){
                this.isChoose1 = true;
                this.isChoose2 = false;
                this.isChoose3 = false;
            }
            if(val == 2){
                this.isChoose2 = true;
                this.isChoose1 = false;
                this.isChoose3 = false;
            }
            if(val == 3){
                this.isChoose3 = true;
                this.isChoose1 = false;
                this.isChoose2 = false;
            }
            this.$nextTick(() => {
                // this.heightRecord = this.$refs.activ.offsetHeight;
            })
        },
        openMore(){
            this.unfold = false;
        },
        closeMore(){
            this.unfold = true;
        },
        aboutMeHeight(){
            // this.aboutMeScroll = this.$refs.adoutMeRef.scrollTop;
            // if(this.heightRecord > 322 && this.aboutMeScroll < 80){
            //     this.unfold = true;
            // }
        },

        // oss图片上传初始化
        initialize(){
            this.$http.get("/oss/auth/url", {
            }).then((res) => {
                // console.log(res.data)
                if(res.data.code == 500){
                    this.isLogined = false;
                    this.softLogout();
                    // this.openLogin();
                    return message.warning('用户信息已失效，请重新登录', 1200);
                } else {
                    this.client = new OSS({
                        region: 'oss-cn-beijing',
                        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
                        accessKeyId: res.data.AccessKeyId,
                        accessKeySecret: res.data.AccessKeySecret,
                        stsToken: res.data.SecurityToken,
                        bucket: 'haierzzfb',
                        useFetch: false,
                        secure:true,
                        multiSelection: false,
                    });
                }
                // alert(this.client );
            }).catch((error) => {
                // alert('出错了');

            });
        },

        // 聊天窗口滚动到底部,默认强制执行
        chatBoxScrollToBottom(force = true){
            // console.log('调用滚动到底部', force);
            // console.log('上次是否在底部', this.chatBoxLastTimeIsAtBottom);
            if(this.chatBoxLastTimeIsAtBottom || this.force){
                // console.log('真实执行滚动到底部', force);
                this.$refs.ol.scrollTop = this.$refs.chatList.offsetHeight;
            }
        },

        //相关推荐
        recommend(){
            // var token = window.localStorage.token;
            // this.$http({
            //     url:"/api/queryAllLives",
            //     method:"get",
            //     params:{}
            // }).then((res) => {
            //     // console.log(res)
            //     if(res.status == 200){
            //         this.liveList = res.data.lives;
            //     }
            // }).catch((error) => {
            //     console.log(error)
            // })
        },
        //获取验证码
        getCode(){
            if(!this.phoneNum){
                return message.warning('请输入手机号', 1200);
            }
            if(!/^1[0-9]{10}$/.test(this.phoneNum)){
                return message.warning('手机号格式错误', 1200);
            }
            if(this.sendCodeData.status!=1 && this.sendCodeData.status!=3) {
                return console.log('重复点击无效');
            }

            this.sendCodeData.status = 2;

            this.$http.post("/api/smsCode", {
                'phoneNum' : this.phoneNum
            }).then((res) =>{
                if(res.data.code == 0){;
                    message.success('发送成功,请注意查收', 1200);
                    this.$refs.codeInput.focus();

                    // 发送倒计时
                    const cd = ()=> {
                        setTimeout(()=>  {
                            if (this.sendCodeData.cd <= 0) {
                                this.sendCodeData.status = 3;
                            } else {
                                this.sendCodeData.cd -= 1;
                                cd();
                            }
                        }, 1000);
                    };
                    this.sendCodeData.cd = 59;
                    this.sendCodeData.status = 4;
                    cd();
                }else if(res.data.code == 500){
                    this.sendCodeData.status = 1;
                    this.phoneNum = "";
                    // alert(res.data.msg);
                    message.error('操作失败,请稍后再试！', 1200);
                }
            }).catch(res => {
                this.sendCodeData.status = 1;
                message.error('操作失败,请稍后再试！', 1200);
                // alert(res);
            });
        },
        //登录
        async submit(){
            if(!this.phoneNum){
                return message.warning('请输入手机号', 1200);
            }
            if(!this.sysCode){
                return message.warning('请输入验证码', 1200);
            }
            
            let res;
            if(this.wxLoginStatus==2 && !this.isLogined){ // 绑定微信
                const WxUserInfo = JSON.parse(window.sessionStorage.getItem("wxLoginInfo"));
                res = await this.$http.post("/api/wechatbindtel", {
                    openid: WxUserInfo.openid,
                    unionid: WxUserInfo.unionid,
                    username: WxUserInfo.nickname,
                    mobile: this.phoneNum,
                    img: WxUserInfo.headimgurl,
                }
                , {
                    emulateJSON: false,
                    params: {
                        smsCode : parseInt(this.sysCode),
                    }
                });
            } else {
                res = await this.$http.post("/api/appLoginBySms", {
                    phoneNum : this.phoneNum,
                    smsCode : parseInt(this.sysCode),
                }
                , {
                    emulateJSON: false,
                    params: {
                        phoneNum : this.phoneNum,
                        smsCode : parseInt(this.sysCode),
                    }
                });
            }

            if(res.data.code == 0 && res.data.msg == "success"){
                this.showLogin = false;//关闭登录页
                this.saveUserInfoToLocal(res.data.token, res.data.userEntity.username, res.data.userEntity.userId, res.data.userEntity.img, res.data.userEntity);
            } else {
                this.sysCode = "";
                message.error(res.data.msg, 3000);
                // this.initialize()
            }
        },

        afterLoginSubmit(res){
            this.saveUserInfoToLocal(res.data.token, res.data.userEntity.username, res.data.userEntity.userId, res.data.userEntity.img, res.data.userEntity);

            message.success('欢迎您' + res.data.userEntity.username + "！", 1500);

            this.$nextTick(() => {
                this.linkWebket();
            });

            // 暂时解决直播问题，重启之
            // location.reload();
        },

        //验证密码
        submitPassword(){
            // console.log(this.livePassword,parseInt(this.password))
            if(!this.password){
                return message.warning('请输入直播密码', 1200);
            }
            if(this.livePassword !== this.password){
                return message.warning('密码输入错误', 1200);
            }
            message.success('欢迎您' + this.userName + "！", 1500);
            window.sessionStorage.setItem("password", this.livePassword);
            this.showPassword = false;
        },
        //关闭蒙层
        closeDialog(e){
            this.showLogin = false;
            // if(e.target == this.$refs.dialog){
            // }
        },
        //关闭密码
        closeDialogPassword(e){
            this.showPassword = false;
            // if(e.target == this.$refs.dialogPassword){
            // }
        },

        // 对uri特殊处理下
        specCookUriData(str){
            if(typeof str=='string'){
                return str.replace('#/index', '');
            } else {
                return str;
            }
        },

        // 从uri初始化
        uriIni(){
            if(!this.isAppEnv) return;
            this.testText = this.specCookUriData(getQueryPara('userid'));
            console.log(this.specCookUriData(getQueryPara('userid')));
            var userId = this.specCookUriData(getQueryPara('userid'));
            window.localStorage.token = this.specCookUriData(getQueryPara('token'));
            this.userName = this.specCookUriData(getQueryPara('username'));
            this.img = this.specCookUriData(getQueryPara('img'));
            // 标记已经登陆
            this.isLogined = true;
            this.getUserInfo(userId);
        },
        // 
        getUserInfo(id){
            console.log(id);
            window.localStorage.Id = id;
            this.$http({
                url: "/api/appGetUser?userId=" + id,
                method: "get",
            }).then(res=>{
                window.localStorage.setItem("user", JSON.stringify(res.body.userEntity));
                if(window.localStorage.getItem("token") && this.streamId){
                    this.linkWebket();
                }
            })
        },

        // // 没有登){
        //     // !必须登陆后才能看直播
        //     if(!window.localStorage.token){
        //         message.warning('请登录后观看直播！', 1200);
        //         this.openLogin();
        //         return false;
        //     } else {
        //         return true;
        //     }
        // },

        // 分享转发
        toShare(){
            const { shareInfo } = this;
            let params = {
                title: shareInfo.title || '正在发布直播平台',
                content: shareInfo.content || '海尔920大会演播厅！',
                url: shareInfo.url || 'https://app.ailive.cloud/app',
                img: shareInfo.img || '',
            };
            if(this.isIosAppEnv){
                window.webkit.messageHandlers.Goshare.postMessage(params);
            } else if(this.isAndAppEnv){
                window.JsInterface.Goshare(params.title, params.content, params.url, params.img);
            }
        },

        // 相关推荐
        handleClickRecommend(id, type, shareTitle, shareImgUrl){
            let params = {
                streamId: id,
                type: type,
                shareTitle,
                shareImgUrl,
            };
            if(this.isIosAppEnv){
                window.webkit.messageHandlers.GotoRecommandWithPrams.postMessage(params);
            } else if(this.isAndAppEnv) {
                window.JsInterface.GotoRecommandWithPrams(id, type, shareTitle, shareImgUrl);
            }
        },

        // 这个方法是为了苹果手机失去焦点后，布局无法自动归位
        hackBlur(){
            // let doc = document.documentElement || document.body;
            // let st = doc.scrollHeight - doc.clientHeight;
            // console.log(st);
            // window.scrollTo(0, st);
            // ios浏览器会卡住
            if(browser.versions.ios){
                this.$refs.pageBottomTag.scrollIntoView(false);
            }
        },
        hackBlurTop(){
            let doc = document.documentElement || document.body;
            let st = doc.scrollHeight - doc.clientHeight;
            // console.log(st);
            window.scrollTo(0, doc.scrollTop + 1);
        },

        doCheckResize(){
            let doc = document.body;
            if (window.orientation === 180 || window.orientation === 0) { 
                console.log('竖屏状态！');
                this.isCrosswise = false;
                doc.style.backgroundColor = '#fff';
                if(this.qualityFullScreen){
                    this.qualityFullScreen = false;
                }
            } 
            if (window.orientation === 90 || window.orientation === -90 ){ 
                console.log('横屏状态！');
                this.isCrosswise = true;
                doc.style.backgroundColor = '#000';
                if(this.quality){
                    this.quality = false;
                }

                // 产品让改成每次全屏播放都有提示
                this.haveReadDisernHint = false;
            }
            
            // 如果ios app内,无需更新高度,更新后会出错
            if(!this.isIosAppEnv || this.isCrosswise){
                if(browser.versions.android && this.chatInputIsFocused){
                    return;
                }
                this.clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                console.log('页面大小变化', this.clientHeight);
                if (browser.versions.ios && browser.versions.weixin) { 
                    this.clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                }
            } else {
                this.clientHeight = iniClientHeight;
            }
        },

        // 检测手机横竖屏状态
        checkResize(){
            let that = this;
            that.doCheckResize();
            
            //判断手机横竖屏状态：
            window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", ()=>{
                that.doCheckResize();
            }, false); 
        },

        shiftFullVideo(){
            if(this.isIosAppEnv) {
                window.webkit.messageHandlers.GotoFullscreen.postMessage({});
            } else if(this.isAndAppEnv){
                window.JsInterface.GotoFullscreen();
            } else {
                this.videoIsFullScreen = !this.videoIsFullScreen;
            }
            this.overdueHiddenVideoControlBar();
        },

        // 劫持全屏按钮点击事件
        hijackFullBtnClick(){
            let eles = document.getElementsByClassName('prism-fullscreen-btn');
            let that = this;
            console.log('满屏按钮个数：', eles.length);
            if(eles.length > 0){
                let ele = eles[0];

                ele.onclick = (e)=>{
                    e.preventDefault();
                    if (e && e.stopPropagation){
                        e.stopPropagation()
                    }else{
                        window.event.cancelBubble = true;
                        window.event.retuenValue = false;
                    }

                    console.log('点击全屏按钮', e);
                    // that.shiftFullVideo();
                    return false;
                };

                ele.ontouchstart = (e)=>{
                    e.preventDefault();
                    if (e && e.stopPropagation){
                        e.stopPropagation()
                    }else{
                        window.evenlt.canceBubble = true;
                        window.event.retuenValue = false;
                    }

                    that.shiftFullVideo();
                    console.log('触摸全屏按钮', e);
                    return false;
                };
            }
        },

        showTvbox(){
            if(false){
                this.tvboxIsDim = false;
            } else {
                this.clickTVBOx = !this.clickTVBOx;
            }
        },
        hideTvbox(){
            this.tvboxIsDim = true;
        },

        // 关闭页面
        closePage(){
            if(this.isIosAppEnv){
                // 必须传一个空参数
                window.webkit.messageHandlers.ClosePage.postMessage({});
            } else if(this.isAndAppEnv){
                window.JsInterface.ClosePage();
            }
        },

        // 监听播放状态
        listenPlayStatus(){
            if(player && typeof player.getStatus=='function'){
                let sts = player.getStatus();
                if(typeof sts=='string'){
                    if(sts!='playing' &&  sts!='play' &&  sts!='init' &&  sts!='error'){
                        if(this.isLogined && typeof player.play=='function'){
                            // 永远播放
                            // player.play();
                        }
                    }

                    if(sts=='playing' || sts=='play'){
                        this.videoIsFirstPlayed = true;
                        this.videoIsPlaying = true;
                    } else {
                        this.videoIsPlaying = false;
                    }

                    if(sts == 'error'){
                        if(this.videoIsFullScreen){
                            this.shiftFullVideo();
                        }
                    }

                    if(sts == 'error' || sts=='ended'){
                        this.liveIsOver = true;
                    } else {
                        this.liveIsOver = false;
                    }
                }
            } else {
                if(this.videoIsFullScreen){
                    this.shiftFullVideo();
                }
            }
        },

        shiftVideoPlay(){
            if(this.videoIsPlaying){
                player.pause();
            } else {
                player.play();
            }
        },
        //切换分辨率
        shiftQuality(){
            this.quality = true;
            this.isOverdueHiddenVideoControlBar = true;
            // console.log(111)
        },
        //切换分辨率(横屏)
        shiftQualityFullScreen(){
            this.qualityFullScreen = true;
            this.isOverdueHiddenVideoControlBar = true;
        },
        //改变画质
        changeQuality(val){
            this.quality = false;
            this.qualityFullScreen = false;
            this.showedVideoControlBar = true;
            this.overdueHiddenVideoControlBar();
            if(val == 1){
                this.thisQuality = 1;
                this.qualityValue = "高清";
                // console.log(player, this.allSource)
                player.pause();
                player.loadByUrl(this.allSource.m3u8_lhd.replace("http:",""));
                player.play();

            }else if(val == 2){
                this.thisQuality = 2;
                this.qualityValue = "标清";
                player.pause();
                // player.loadByUrl(this.allSource.m3u8_lsd.replace("http:",""));
                // player.play();

            }else if(val == 3){
                this.thisQuality = 3;
                this.qualityValue = "流畅";
                player.pause();
                player.loadByUrl(this.allSource.m3u8_lld.replace("http:",""));
                player.play();
            }
        },
        // 阅读提示
        readDisernHint(){
            this.haveReadDisernHint = true;
        },

        // 保存用户数据到本地
        saveUserInfoToLocal(token='', userName='', userId='', img='', user=''){
            // 标记已经登陆
            this.isLogined = true;
            console.log(user);
            if(token != ''){
                window.localStorage.token = token;
                this.token = token;
            }

            if(userName != ''){
                window.localStorage.userName = userName;
                this.userName = userName;
            }

            if(img != ''){
                window.localStorage.img = img;
                this.img = img;
            }

            if(userId != ''){
                window.localStorage.Id = userId;
                this.userId = userId;
            }

            if(user!='' && user != {}){
                window.localStorage.setItem("user", JSON.stringify(user));
            }
            // 微信登录没有wytoken，所以需要判断
            if(JSON.parse(window.localStorage.getItem("user")).wyToken){
                this.linkWebket();
            }
        },
        // 观看人数+1
        visiterAdd(){
            this.$http.post("/api/visit?streamId=" + this.streamId).then(res=>{
                
            })
        },

        // 微信jdk初始化 暂时没用
        // wxEnvIni(){
        //     wx.config({
        //         debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        //         appId: 'wx65be8936093075fe', // 必填，公众号的唯一标识
        //         timestamp: new Date().getTime(), // 必填，生成签名的时间戳
        //         nonceStr: 'faoejfoaejfoaw', // 必填，生成签名的随机串
        //         signature: 'zzfb',// 必填，签名
        //         jsApiList: [
        //             'updateAppMessageShareData',
        //             'updateTimelineShareData',
        //         ] // 必填，需要使用的JS接口列表
        //     });

        //     wx.ready(()=>{
        //         log('微信jdk初始化成功', err);
        //     });

        //     wx.error(err=>{
        //         log('微信jdk初始化出错', err);
        //     });
        // },

        async wxBindPhone(){},

        async wxUserLogin(){
            const {wxLoginStatus, phoneNum} = this;
            const WxUserInfo = JSON.parse(window.sessionStorage.getItem("wxLoginInfo"));
            if(window.localStorage.getItem("token")){
                
            }else{
                return this.openLogin()
            }
            if(
                wxLoginStatus==2
                // || true
                ){
                // alert(12345);
                const res = await this.$http.post("/api/wechatLogin", {
                        openid: WxUserInfo.openid,
                        unionid: WxUserInfo.unionid,
                        username: WxUserInfo.nickname,
                        mobile: phoneNum,
                        img: WxUserInfo.headimgurl,

                    }
                    , {
                        emulateJSON: false
                    }
                    );

                // alert(5661616);
                if(res.data.code == 0){
                    if(res.data.msg=='success'){
                        this.afterLoginSubmit(res);
                        // message.success(JSON.stringify(res.data));
                    }
                } else {
                    message.success(res.data.msg);
                    console.log(res.data.msg);
                }
            }
        },

        // 微信登陆
        async wxLogin(){
            if(this.isLogined || !this.isWxEnv) return;

            const {wxLoginCode, wxLoginState, wxLoginStatus} = this;

            if(wxLoginStatus==0){
                if(typeof wxLoginState=='string' && wxLoginState.indexOf('zzfb') != -1){
                    this.wxLoginStatus = 1;
                    const res = await this.$http.get("/wechat/getAccessToken", {
                        params: {
                            code: wxLoginCode
                        }
                    });
                    if(res.data.code == 0){
                        this.wxLoginStatus = 2;
                        if(res.data.data.nickname){
                            window.sessionStorage.setItem("wxLoginInfo", JSON.stringify(res.data.data));
                            this.wxUserLogin();
                        } else {
                            console.log("判断失败", res.data.data);
                        }        
                    } else {
                        this.wxLoginStatus = 3;
                        console.log(res.data.msg);
                    }
                } else {
                    const baseUrl = process.env.NODE_ENV=='production' ? 'https://app.ailive.cloud/app' : 'https://test.ailive.cloud/app';
                    const loginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
                        + 'wx65be8936093075fe'
                        + '&redirect_uri='
                        + encodeURI(baseUrl + '?streamId=' + this.streamId)
                        + '&response_type=code&scope=snsapi_userinfo&state=zzfb#wechat_redirect';
                    // message.success(baseUrl + '?id=' + this.id);
                    location.href = loginUrl;
                }
            } else if(wxLoginStatus == 3)  {
                // 登录失败怎么办呢？
                return;
            } else {
                return;
            }
        },
    },
}
</script>